<template>
  <div class="p-16px">
    <el-card>
      <el-space wrap :size="24">
        <el-space>
          <el-button type="primary" @click="handleCreate">新建商品</el-button>
          <el-button>导入</el-button>
          <el-button>导出</el-button>
          <el-button>模板下载</el-button>
        </el-space>
        <div class="flex items-center whitespace-nowrap">
          商品类别：
          <GoodsCategorySelect v-model="params.goodsCategoryId" />
        </div>
        <div class="flex items-center whitespace-nowrap">
          商品名称：
          <el-input placeholder="请输入内容" clearable></el-input>
        </div>
        <div class="flex items-center whitespace-nowrap">
          商品编号：
          <el-input placeholder="请输入内容" clearable></el-input>
        </div>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-space>
    </el-card>
    <el-card class="mt-16px">
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="编号" width="80" />
        <el-table-column prop="goodsCode" label="商品编号" min-width="180" />
        <el-table-column prop="goodsName" label="商品名称" min-width="180" />
        <el-table-column prop="goodsPrice" label="单价" min-width="180" />
        <el-table-column
          prop="goodsCategoryName"
          label="商品类别"
          min-width="180"
        />
        <el-table-column prop="goodsSort" label="商品排序" min-width="180" />
        <el-table-column prop="isEnable" label="状态" min-width="180">
          <template #default="scope">
            <el-tag :type="scope.row.isEnable === 1 ? 'success' : 'danger'">
              {{ scope.row.isEnable === 1 ? "上架" : "下架" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column prop="updateTime" label="更新时间" min-width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-16px flex justify-end">
        <el-pagination
          v-model:current-page="params.current"
          v-model:page-size="params.size"
          layout="prev, pager, next"
          background
          :total="total"
          @current-change="fetchList"
        />
      </div>
    </el-card>
    <el-dialog
      :title="form.id ? '编辑商品' : '新建商品'"
      v-model="isShowDialog"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="form.goodsName" />
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="form.goodsPrice" />
        </el-form-item>
        <el-form-item label="商品排序">
          <el-input-number v-model="form.goodsSort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="form.goodsDesc" />
        </el-form-item>
        <el-form-item label="商品类型">
          <GoodsCategorySelect
            v-model="form.goodsCategoryId"
            @changeLabel="handleChangeGoodsCategory"
          />
        </el-form-item>
        <el-form-item label="可加热">
          <el-switch
            v-model="form.hotEnable"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="缩略图">
          <el-upload
            :action="commonStore.common.uploadUrl"
            list-type="picture-card"
            :on-success="(res) => handleUploadSuccess(res, 'thumbnailPicUrl')"
            :headers="commonStore.common.headers"
            :data="commonStore.common.data"
            :show-file-list="false"
          >
            <img
              v-if="form.thumbnailPicUrl"
              :src="form.thumbnailPicUrl"
              class="w-128px h-128px"
            />
            <el-icon v-else>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情图">
          <el-upload
            :action="commonStore.common.uploadUrl"
            list-type="picture-card"
            :on-success="(res) => handleUploadSuccess(res, 'detailPicUrl')"
            :headers="commonStore.common.headers"
            :data="commonStore.common.data"
            :show-file-list="false"
          >
            <img
              v-if="form.detailPicUrl"
              :src="form.detailPicUrl"
              class="w-128px h-128px"
            />
            <el-icon v-else>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
          >
            提交
          </el-button>
          <el-button @click="isShowDialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import GoodsCategorySelect from "@/components/Select/GoodsCategorySelect.vue";
import { useCommonStoreHook } from "@/store/modules/common";
import dayjs from "dayjs";

const commonStore = useCommonStoreHook();
const params = ref({
  current: 1,
  size: 10,
  goodsCategoryId: "",
  goodsName: "",
  goodsCode: "",
});
const tableData = ref([]);
const defaultForm = {
  goodsName: "",
  goodsPrice: "",
  goodsDesc: "",
  goodsCategoryId: "",
  goodsCategoryName: "",
  // 可加热
  hotEnable: 0,
  // 缩略图
  thumbnailPicUrl: "",
  // 详情图
  detailPicUrl: "",
};
const form = ref({
  ...defaultForm,
});
const isShowDialog = ref(false);
const loading = ref(false);
const submitLoading = ref(false);
const total = ref(0);

const handleCreate = () => {
  form.value = {
    ...defaultForm,
  };
  isShowDialog.value = true;
};
const handleEdit = (row) => {
  form.value = {
    ...defaultForm,
    ...row,
  };
  isShowDialog.value = true;
};
const handleChangeGoodsCategory = ({ label }) => {
  form.value.goodsCategoryName = label;
};
const fetchList = () => {
  loading.value = true;
  commonStore
    .queryGoodsPage(params.value)
    .then((res) => {
      tableData.value = res.records.map((item) => ({
        ...item,
        createTime: dayjs(item.createTime).format("YYYY-MM-DD HH:mm:ss"),
        updateTime: dayjs(item.updateTime).format("YYYY-MM-DD HH:mm:ss"),
      }));
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleUploadSuccess = (res, key) => {
  form.value[key] = res.data.url;
};
const handleSearch = () => {
  params.value.current = 1;
  fetchList();
};
const handleSubmit = () => {
  submitLoading.value = true;
  if (form.value.id) {
    commonStore
      .updateGoods(form.value)
      .then((res) => {
        ElMessage.success("操作成功");
        isShowDialog.value = false;
        fetchList();
      })
      .finally(() => {
        submitLoading.value = false;
      });
  } else {
    commonStore
      .addGoods(form.value)
      .then((res) => {
        ElMessage.success("操作成功");
        isShowDialog.value = false;
        fetchList();
      })
      .finally(() => {
        submitLoading.value = false;
      });
  }
};
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "删除中...";
        commonStore
          .delGoods({ id: row.id })
          .then(() => {
            done();
            ElMessage.success("删除成功");
            handleSearch();
          })
          .finally(() => {
            instance.confirmButtonLoading = false;
            instance.confirmButtonText = "确定";
          });
      } else {
        done();
      }
    },
  });
};
onMounted(() => {
  handleSearch();
});
</script>

<style lang="scss" scoped></style>
